package com.acron.xrpc.registry;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.Builder;

/**
 * RPC注册中心
 * Created by acron on 2022/2/19.
 */
@Builder
public class RpcRegistry {

    private int port = 8080;

    public static void main(String[] args) {
        RpcRegistry registry = RpcRegistry.builder().port(8080).build();
        registry.register();
    }

    private void register() {
        int processorsNum = Runtime.getRuntime().availableProcessors();
        EventLoopGroup bossGroup = new NioEventLoopGroup(processorsNum);
        EventLoopGroup workGroup = new NioEventLoopGroup(processorsNum);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ChannelFuture channelFuture = serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 定制协议解码器
                            ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                                    0, 4, 0, 4))
                                    // 定制协议编码器
                                    .addLast("frameEncoder", new LengthFieldPrepender(4))
                                    // 对象参数编码器
                                    .addLast("objectEncoder", new ObjectEncoder())
                                    // 对象参数解码器
                                    .addLast("objectDecoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)))
                                    // 业务逻辑
                                    .addLast("handler", new RpcHandler());

                        }
                    }).bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
